package com.glidebitmappool.internal;

import ohos.agp.utils.Color;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.media.image.PixelMap;
import ohos.media.image.common.AlphaType;
import ohos.media.image.common.ImageInfo;
import ohos.media.image.common.PixelFormat;
import ohos.media.image.common.Size;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

/**
 * 缓存位图池
 *
 * @author renpengfei
 * @since 2021-03-12
 */
public class LruBitmapPool implements BitmapPool {
    private static final String TAG = LruBitmapPool.class.getSimpleName();
    private static final PixelFormat DEFAULT_CONFIG = PixelFormat.ARGB_8888;
    private static final int TRIM_MEMORY_BACKGROUND = 40;
    private static final int TRIM_MEMORY_UI_HIDDEN = 20;
    private final int two = 2;

    private final LruPoolStrategy strategy;
    private final Set<PixelFormat> allowedConfigs;
    private final int initialMaxSize;
    private final BitmapTracker tracker;

    private int maxSize;
    private int currentSize;
    private int hits;
    private int misses;
    private int puts;
    private int evictions;

    private int domain = 0x001;
    private HiLogLabel logLabel = new HiLogLabel(HiLog.LOG_APP, domain, TAG);

    private LruBitmapPool(int maxSize, LruPoolStrategy strategy, Set<PixelFormat> allowedConfigs) {
        this.initialMaxSize = maxSize;
        this.maxSize = maxSize;
        this.strategy = strategy;
        this.allowedConfigs = allowedConfigs;
        this.tracker = new NullBitmapTracker();
    }

    /**
     * 构建一定数量的缓存池
     *
     * @param maxSize
     */
    public LruBitmapPool(int maxSize) {
        this(maxSize, getDefaultStrategy(), getDefaultAllowedConfigs());
    }

    /**
     * 构建一定数量的缓存池并添加配置
     *
     * @param maxSize
     * @param allowedConfigs
     */
    public LruBitmapPool(int maxSize, Set<PixelFormat> allowedConfigs) {
        this(maxSize, getDefaultStrategy(), allowedConfigs);
    }

    @Override
    public int getMaxSize() {
        return maxSize;
    }

    @Override
    public synchronized void setSizeMultiplier(float sizeMultiplier) {
        maxSize = Math.round(initialMaxSize * sizeMultiplier);
        evict();
    }

    @Override
    public synchronized void put(PixelMap bitmap) {
        if (bitmap == null) {
            throw new NullPointerException("Bitmap must not be null");
        }
        if (bitmap.isReleased()) {
            throw new IllegalStateException("Cannot pool recycled bitmap");
        }

        if (!bitmap.isEditable() || strategy.getSize(bitmap) > maxSize
                || !allowedConfigs.contains(bitmap.getImageInfo().pixelFormat)) {
            if (HiLog.isLoggable(domain, TAG, HiLog.LOG_APP)) {
                HiLog.info(logLabel, "Reject bitmap from pool"
                        + ", bitmap: " + strategy.logBitmap(bitmap)
                        + ", is mutable: " + bitmap.isEditable()
                        + ", is allowed config: " + allowedConfigs.contains(bitmap.getImageInfo().pixelFormat));
            }
            bitmap.release();
            return;
        }

        final int size = strategy.getSize(bitmap);
        strategy.put(bitmap);
        tracker.add(bitmap);

        puts++;
        currentSize += size;

        if (HiLog.isLoggable(domain, TAG, HiLog.LOG_APP)) {
            HiLog.info(logLabel, "Put bitmap in pool=" + strategy.logBitmap(bitmap));
        }
        dump();

        evict();
    }

    private void evict() {
        trimToSize(maxSize);
    }

    @Override
    public PixelMap get(int width, int height, PixelFormat config) {
        PixelMap result = getDirtyOrNull(width, height, config);
        if (result != null) {
            result.writePixels(Color.TRANSPARENT.getValue());
        } else {
            PixelMap.InitializationOptions initializationOptions = new PixelMap.InitializationOptions();
            initializationOptions.size = new Size(width,height);
            initializationOptions.pixelFormat = config;
            result = PixelMap.create(initializationOptions);
        }
        return result;
    }

    @Override
    public PixelMap getDirty(int width, int height, PixelFormat config) {
        PixelMap result = getDirtyOrNull(width, height, config);
        if (result == null) {
            PixelMap.InitializationOptions initializationOptions = new PixelMap.InitializationOptions();
            initializationOptions.size = new Size(width,height);
            initializationOptions.pixelFormat = config;
            result = PixelMap.create(initializationOptions);
        }
        return result;
    }

    private synchronized PixelMap getDirtyOrNull(int width, int height, PixelFormat config) {
        // Config will be null for non public config types, which can lead to transformations naively
        // passing in null as the requested config here. See issue #194.
        final PixelMap result = strategy.get(width, height, config != null ? config : DEFAULT_CONFIG);
        if (result == null) {
            if (HiLog.isLoggable(domain, TAG, HiLog.DEBUG)) {
                HiLog.debug(logLabel, "Missing bitmap=" + strategy.logBitmap(width, height, config));
            }
            misses++;
        } else {
            hits++;
            currentSize -= strategy.getSize(result);
            tracker.remove(result);
            normalize(result);
        }
        if (HiLog.isLoggable(domain, TAG, HiLog.LOG_APP)) {
            HiLog.info(logLabel, "Get bitmap=" + strategy.logBitmap(width, height, config));
        }
        dump();

        return result;
    }

    /**
     * Setting these two values provides Bitmaps that are essentially equivalent to those returned
     * from Bitmap.createBitmap.
     *
     * @param bitmap
     */
    private static void normalize(PixelMap bitmap) {
        maybeSetAlpha(bitmap);
        maybeSetPreMultiplied(bitmap);
    }

    private static void maybeSetAlpha(PixelMap bitmap) {
        bitmap.setAlphaType(AlphaType.UNPREMUL);
    }

    private static void maybeSetPreMultiplied(PixelMap bitmap) {
        bitmap.setAlphaType(AlphaType.PREMUL);
    }

    @Override
    public void clearMemory() {
        if (HiLog.isLoggable(domain, TAG, HiLog.DEBUG)) {
            HiLog.debug(logLabel, "clearMemory");
        }
        trimToSize(0);
    }

    @Override
    public synchronized void trimMemory(int level) {
        if (HiLog.isLoggable(domain, TAG, HiLog.DEBUG)) {
            HiLog.debug(logLabel, "trimMemory, level=" + level);
        }

        /**
         * 20：例如，由于用户触摸了设备上的Home键，因此应用程序UI被隐藏。您的应用程序应释放分配给UI显示的资源，以释放内存。
         */

        /**
         * 40：设备的内存不足，并且您的应用程序位于LRU列表的顶部。该系统不太可能杀死您的应用程序。
         * 为了将您的应用程序进程在缓存中保留更长的时间，您的应用程序应通过释放一些易于恢复的资源来增加可用的系统内存。
         * 这样，您的应用程序可以平稳地返回到前台，而不必重新启动。
         */

        /**
         * 原库 中对应具体数值 int TRIM_MEMORY_BACKGROUND = 40
         */
        if (level >= TRIM_MEMORY_BACKGROUND) {
            clearMemory();
            /**
             * 原库 中对应具体数值 int TRIM_MEMORY_UI_HIDDEN = 20
             */
        } else if (level >= TRIM_MEMORY_UI_HIDDEN) {
            trimToSize(maxSize / two);
        }
    }

    private synchronized void trimToSize(int size) {
        while (currentSize > size) {
            final PixelMap removed = strategy.removeLast();
            if (removed == null) {
                if (HiLog.isLoggable(domain, TAG, HiLog.WARN)) {
                    HiLog.warn(logLabel, "Size mismatch, resetting");
                    dumpUnchecked();
                }
                currentSize = 0;
                return;
            }
            tracker.remove(removed);
            currentSize -= strategy.getSize(removed);
            evictions++;
            if (HiLog.isLoggable(domain, TAG, HiLog.DEBUG)) {
                HiLog.debug(logLabel, "Evicting bitmap=" + strategy.logBitmap(removed));
            }
            dump();
            removed.release();
        }
    }

    private void dump() {
        if (HiLog.isLoggable(domain, TAG, HiLog.LOG_APP)) {
            dumpUnchecked();
        }
    }

    private void dumpUnchecked() {
        HiLog.info(logLabel, "Hits=" + hits + ", misses=" + misses + ", puts=" + puts + ", evictions=" + evictions
                + ", currentSize=" + currentSize + ", maxSize=" + maxSize
                + System.lineSeparator() + "Strategy=" + strategy);
    }

    private static LruPoolStrategy getDefaultStrategy() {
        final LruPoolStrategy strategy;

        /**
         * 原库  api 19以上
         */
        strategy = new SizeConfigStrategy();

        return strategy;
    }

    private static Set<PixelFormat> getDefaultAllowedConfigs() {
        Set<PixelFormat> configs = new HashSet<>();
        configs.addAll(Arrays.asList(PixelFormat.values()));

        /**
         * 原库  api 19以上
         */
        configs.add(null);
        return Collections.unmodifiableSet(configs);
    }

    /**
     * 位图接口类
     *
     * @since 2021-03-12
     */
    private interface BitmapTracker {
        void add(PixelMap bitmap);

        void remove(PixelMap bitmap);
    }

    /**
     * 位图调试类
     *
     * @since 2021-03-12
     */
    @SuppressWarnings("unused")
    // Only used for debugging
    private static class ThrowingBitmapTracker implements BitmapTracker {
        private final Set<PixelMap> bitmaps = Collections.synchronizedSet(new HashSet<PixelMap>());

        @Override
        public void add(PixelMap bitmap) {
            ImageInfo imageInfo = bitmap.getImageInfo();
            Size size = imageInfo.size;
            if (bitmaps.contains(bitmap)) {
                throw new IllegalStateException(
                        "Can't add already added bitmap: " + bitmap + " [" + size.width + "x" + size.height + "]");
            }
            bitmaps.add(bitmap);
        }

        @Override
        public void remove(PixelMap bitmap) {
            if (!bitmaps.contains(bitmap)) {
                throw new IllegalStateException("Cannot remove bitmap not in tracker");
            }
            bitmaps.remove(bitmap);
        }
    }

    /**
     * 空位图
     *
     * @since 2021-03-12
     */
    private static class NullBitmapTracker implements BitmapTracker {
        @Override
        public void add(PixelMap bitmap) {
            // Do nothing.
        }

        @Override
        public void remove(PixelMap bitmap) {
            // Do nothing.
        }
    }
}
